use IO::Socket;
$SOCKBLOCKSIZE = (100*1024);
sub upload
{
	print "uploading...\n" if $debug;
	my ($sock,$filename) = @_;
	if(!(open IN,"<$filename"))
	{
		goto error;
	}
	print $sock "filename:$filename\n";
	my $filesize = -s $filename;
	print $sock "filesize:$filesize\n";
	binmode(IN);
	my $sentsize = 0;
	my $blocksize = $filesize > ($SOCKBLOCKSIZE) ? ($SOCKBLOCKSIZE):$filesize;
	while(($sent = read(IN,$buf,$blocksize)) > 0)
	{		
		$sock->send($buf,$readsize);
		$filesize -= $sent;
		$blocksize = $filesize > ($SOCKBLOCKSIZE) ? ($SOCKBLOCKSIZE):$filesize;
	}
	<$sock>;#read "svr:end\n";
	close(IN);
	return 0;
error:
	print "error :$!\n" if $debug;
	close(IN);
	return -1;
}

sub download
{
	print "downloading...\n" if $debug;
	my ($sock) = @_;
	if(!(<$sock> =~ /^filename:([^\r\n]*)/))
	{
		goto error;
	}
	my $filename = $1;
	if(!(<$sock> =~ /^filesize:(\d+)/))
	{
		goto error;
	}
	my $filesize = $1;
	if($filesize <= 0)
	{
		goto error;
	}
	if(!(open OUT,">$filename"))
	{
		goto error;
	}
	binmode(OUT);
	my $blocksize = $filesize > ($SOCKBLOCKSIZE) ? ($SOCKBLOCKSIZE):$filesize; 
	my $read;
	while(($read = read($sock,$buf,$blocksize)) > 0)
	{
		print OUT $buf;
		$filesize -= $read;
		$blocksize = $filesize > ($SOCKBLOCKSIZE) ? ($SOCKBLOCKSIZE):$filesize; 
	}
	print $sock "svr:end\n" if $debug;
	close(OUT);
	return 0;
error:
	close(OUT);
	return -1;
}
1;